package com.example.vspm.interceptor;

import com.example.vspm.entity.Person;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@CrossOrigin(origins = "http://localhost:9090")
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object object = request.getSession().getAttribute("person");

//首先判断是否是在登陆中，如果是，则直接跳过下方的强制登录，防止反复重定向
        if ("/person/index".contains(request.getRequestURI()) || "/person/login".contains(request.getRequestURI())) {
            System.out.println("进行登录操作中"+request.getRequestURI());
            return true;
        }
//如果没登录，强制登录
        if (object == null) {
            System.out.println("未登录成功、session中没有数据");
//            System.out.println("没登录" + request.getRequestURI());
            response.sendRedirect("/person/index");
            return false;
        }



//        Person person = (Person)object;
//        else if (!request.getRequestURI().contains(cap(person.getCapacity()))){
//            System.out.println("乱输网址");
//            response.sendRedirect("/person/index");
////           response.sendRedirect("/person"+cap(person.getCapacity())+"/index");
//            return false;
//        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
    public String cap(String cap){
        String cp = "";
        switch (cap){
            case "100":
                cp = "/poster";
                break;
            case "010":
                cp = "/sender";
                break;
            case "001":
                cp = "/receiver";
                break;
            case "111":
                cp = "/grant";
                break;
            default:
                cp = "index";
                break;
        }
        return cp;
    }
}
